package com.jhlishero.study.jdk8.chapter05;

import org.junit.Before;
import org.junit.Test;

import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * 数值流
 *      IntStream
 *      DoubleStream
 *      LongStream
 */
public class Demo5_6_MapToNumberStream {

    private List<User> userList = new ArrayList<>();
    @Before
    public void init() {
        userList.add(new User(1));
        userList.add(new User(3));
        userList.add(new User(5));
        userList.add(new User(7));
        userList.add(new User(9));
    }

    /**
     * 映射到数值流
     */
    @Test
    public void test01_01() {
        IntStream is = userList.stream().mapToInt(user -> user.getId());
        System.out.println("sum=" + is.sum());

        is = userList.stream().mapToInt(user -> user.getId()); //重新获取流，因为调用IntStream.sum()方法后，会自动关闭流
        System.out.println("count=" + is.count());

        is = userList.stream().mapToInt(user -> user.getId());
        System.out.println("average=" + is.average());

        is = userList.stream().mapToInt(user -> user.getId());
        System.out.println("min=" + is.min());

        is = userList.stream().mapToInt(user -> user.getId());
        System.out.println("max=" + is.max());
    }


    /**
     * 转换回对象流
     */
    @Test
    public void test01_02() {
        IntStream intStream = userList.stream().mapToInt(user -> user.getId());
        Stream<Integer> stream = intStream.boxed();
        Optional<Integer> opt = stream.min(Comparator.comparing(a->a));
        opt.ifPresent(System.out::println);
    }


    /**
     * 设置OptionalInt的默认值
     */
    @Test
    public void test01_03() {
        List<User> users = new ArrayList<>();

        OptionalInt maxValue = users.stream()
                .mapToInt(user -> user.getId())
                .max();

        int max = maxValue.orElse(9999);//如果没有最大值的话，显示提供一个默认最大值
        System.out.println("max=" + max);
    }

    /**
     * 数据范围
     */
    @Test
    public void test02() {
        System.out.print("IntStream.range result =       ");
        IntStream intStreamRange = IntStream.range(1, 10); //>=1 and <10
        intStreamRange.forEach(a -> System.out.print(a + "  "));
        System.out.println();
        System.out.print("IntStream.rangeClosed result = ");
        IntStream intStreamRangeClosed = IntStream.rangeClosed(1, 10); // >=1 and <=10
        intStreamRangeClosed.forEach(a -> System.out.print(a + "  "));
    }


    class User {
        private int id;

        public User(int id) {
            this.id = id;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }
    }
}
